package com.zhangsun.newMvvm.base.view;

import android.arch.lifecycle.Observer;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.widget.Toast;

import com.zhangsun.newMvvm.base.bean.LoadingDialogBean;
import com.zhangsun.newMvvm.base.bean.ResponseData;
import com.zhangsun.newMvvm.base.enums.PagingLoadTypeEnum;
import com.zhangsun.newMvvm.base.model.BaseViewModel;

public abstract class BaseActivity<VDB extends ViewDataBinding, VM extends BaseViewModel> extends BaseNoModelActivity<VDB> {

    protected VM viewModel;
    protected Page page;

    @Override
    public void init(Bundle savedInstanceState) {
        viewModel = initViewModel();
        page = new Page();
        initObserve();
        initView();
        initData();
    }

    /**
     * 初始化ViewModel
     */
    protected abstract VM initViewModel();

    /**
     * 初始化视图
     */
    protected abstract void initView();

    /**
     * 初始化数据
     */
    protected abstract void initData();

    /**
     * 监听当前ViewModel中 showDialog和error的值
     */
    private void initObserve() {
        if (viewModel == null) {
            return;
        }
        viewModel.getLoadingDialog().observe(this, (Observer<LoadingDialogBean>) loadingDialogBean -> {
            if (loadingDialogBean != null && loadingDialogBean.isShow()) {
                showDialog(loadingDialogBean.getMsg());
            } else {
                dismissDialog();
            }
        });
        viewModel.getError().observe(this, (Observer<ResponseData>) this::showError);
        viewModel.getPagingLoadType().observe(this, (Observer<PagingLoadTypeEnum>) this::finishByPagingLoadType);
    }

    /**
     * ViewModel层发生了错误
     */
    protected void showError(ResponseData responseData) {
        Toast.makeText(this, responseData.getMessage(), Toast.LENGTH_LONG).show();
    }

    /**
     * 根据加载类型执行
     *
     * @param pagingLoadTypeEnum 加载类型
     */
    protected void finishByPagingLoadType(PagingLoadTypeEnum pagingLoadTypeEnum) {
    }

    protected class Page {

        private long total = 0;

        private long current = 1;

        private long size = 10;

        public long getTotal() {
            return total;
        }

        public void setTotal(long total) {
            this.total = total;
        }

        public long getCurrent() {
            return current;
        }

        public void setCurrent(long current) {
            this.current = current;
        }

        public long getSize() {
            return size;
        }

        public void setSize(long size) {
            this.size = size;
        }
    }

}
